package com.woniuxy.util;

import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;

import java.text.ParseException;
import java.util.Map;


/**
 * jwt的工具类
 */
public class JWTUtil {
    //设置密钥
    private static final String secretKey = "天王盖地虎，宝塔镇河妖";

    /**
     * 创建jwt
     *
     * @param map
     * @return
     * @throws JOSEException
     */
    public static String createJWT(Map map) throws JOSEException {
        //头部
        JWSHeader header = new JWSHeader
                .Builder(JWSAlgorithm.HS256)
                .type(JOSEObjectType.JWT).build();

        //载荷(用户信息)
        Payload payload = new Payload(map);

        //签名(头部+载荷+密钥)
        JWSObject jwsObject = new JWSObject(header, payload);

        //将密钥进行加密
        MACSigner macSigner = new MACSigner(secretKey);
        //将密钥放入签名中
        jwsObject.sign(macSigner);

        //返回jwt字符串
        return jwsObject.serialize();
    }

    /**
     * 解密jwt
     *
     * @param jwt
     * @return
     * @throws ParseException
     * @throws JOSEException
     */
    public static Boolean decode(String jwt) throws ParseException, JOSEException {
        //反序列化
        JWSObject jwsObject = JWSObject.parse(jwt);
        MACVerifier macVerifier = new MACVerifier(secretKey);
        //解密
        return jwsObject.verify(macVerifier);
    }

    public static Map getUserMap(String jwt) throws ParseException {
        //反序列化
        JWSObject jwsObject = JWSObject.parse(jwt);
        Payload payload = jwsObject.getPayload();
        return payload.toJSONObject();
    }

}
